package com.chinasoft.carservice.controller;

import com.chinasoft.carservice.service.CarService;
import com.chinasoft.ms.dto.CarDTO;
import com.chinasoft.ms.dto.RentalRequest;
import com.chinasoft.ms.pojo.Car;
import com.chinasoft.ms.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(("/api"))
public class CarController {

    @Autowired
    private CarService carService;

    @PostMapping("/cars/number/{pageNum}/size/{pageSize}")
    public Result<List<CarDTO>> getAllCars(@RequestBody CarDTO query,
                                           @PathVariable Integer pageNum,
                                           @PathVariable Integer pageSize) {
        List<CarDTO> carDTOs = carService.searchCarDTOs(query);
        return new Result<>(200, "Success", carDTOs);
    }

    /**
     * 条件查询车辆信息（DTO传输）
     */
    @PostMapping("/search")
    public Result<List<CarDTO>> searchCars(@RequestBody CarDTO queryDto) {
        List<CarDTO> carDTOs = carService.searchCarDTOs(queryDto);
        return new Result<>(200, "Success", carDTOs);
    }

    /**
     * 添加新车（DTO传输）
     */
    @PostMapping("/cars/add/")
    public Result<CarDTO> addCar(@RequestBody CarDTO carDTO) {
        CarDTO savedCarDTO = carService.addCar(carDTO);
        return new Result<>(200, "添加成功", savedCarDTO);
    }

    /**
     * 更新车辆信息（DTO传输）
     */
    @PutMapping("/cars/update/")
    public Result<CarDTO> updateCar(@RequestBody CarDTO carDTO) {
        CarDTO updatedCarDTO = carService.updateCar(carDTO);
        return new Result<>(200, "更新成功", updatedCarDTO);
    }

    /**
     * 删除车辆
     */
    @DeleteMapping("/cars/delete/{id}")
    public Result deleteCar(@PathVariable("id") Long id) {
        System.out.println(">>>> 删除方法被调用，ID=" + id); // 添加日志
        carService.deleteCar(id);
        return new Result(200, "删除成功");
    }


    @PostMapping("/cars/rent/")
    public Result rentCar(@RequestBody RentalRequest request) {
        boolean success = carService.rentCar(
                request.getCarId(),
                request.getUserId(),
                request.getRentalStart(),
                request.getRentalEnd()
        );
        return success ? new Result(200, "租车成功") : new Result(500, "租车失败");
    }

    @PostMapping("/cars/return/")
    public Result returnCar(@RequestParam Long CarId) {
        boolean success = carService.returnCar(CarId);
        return success ? new Result(200, "还车成功") : new Result(500, "还车失败");
    }

}
